Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error: django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty
I am currently attempting to update django from 1.4 to 2.0 after many syntax corrections I have run into this error when trying to run the server. I am updating django by having installed the latest version on my previous directory. From everything that ive read online, the SECRET_KEY should be set in the settings.py which it is in my case. django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. If anyone has any resolutions please let me know as I have been struggling with this error for a couple of days now. I understand this may be an issue in the way I am updating so if anyone has more in depth information on updating django that would be very helpful as well. -
Why use dj-stripe or pinax-stripe instead of vanilla stripe?
It seems to me that stripe app is fairly easy to use. What are compelling reasons to consider using dj-stripe of pinax-stripe? -
How to add value in multi dimensions dictionary?
I have a column in MySQL "abc" contains data => demo1, demo1, demo2, demo2 and another column name value data => abc1, abc2, abc3, abc4 how to convert that into a dictionary like { 'demo1': {'abc1', 'abc2'}, 'demo2' : {'abc3', 'abc4'} } for branch in get_branch: branch_array[branch.abc].append( branch.value) for branch in get_branch: branch_array[branch.abc] = branch.value But nothing worked properly -
Access dictionary position in Django template
I have this dictionary in my Django template using {{ item }}: dict_items([('user_id', 28), ('id', 10), ('nome', 'Depósito'), ('informacoes_complementares', 'Depósito central'), ('_state', <django.db.models.base.ModelState object at 0x7f8ea009f208>)]) How do I get the "id" and "nome"? I'm using Django 2.1.7. Thank you. -
Cannot Publish/Deploy Django/Python site in local IIS (through Visual Studio publish)
I had trouble deploying to local IIS my DjangoWebProject from Visual Studio (2019). 1) This is for Windows 10 environment. 2) Used stack: Python/Django/MongoDB/Javascript/D3 3) IIS works and successfully shows the default IIS site (tried from localhost and another machine) 4) Everything works great! I could successfully code/build the site and tested everything is working in debug mode (from VS) - e.g. it opens up http://localhost:<portnumber> in Chrome/EDge and the whole website works perfectly with all the form submission etc. etc. 3) Now I wanted to create the internal site published so other users can access and I tried Publish option... WebpublishMethod: MSDeploy Server Name: <my machine name> Site name: Default Web Site Destination URL: <my machine name>.corp.<my company>.com Validate Connection : Successful Other conf details: ExcludeAppData: False SkipExtraFileOnServer: True MSDeployPublishMethod: InProc EnableMSDeploybackup: True It gets published and it creates all the folder structure and everything (including resource files etc. needed) in the C:\inetpub\wwwroot\app location and the folder structure is consistent with the Visual Studio folder structure for code - it shows all the files like __init__.py forms.py models.py tests.py views.py etc. plus all the required javascript and d3 code and everything. BUT THE PROBLEM: When I go to the … -
Deploying Django from gitlab to windows VM using Jenkins
I am looking for solution to deploy Django application on Windows Server. I tried to do it in several ways with no effect. Architecture: 1. Host: Windows Serve with Apache WSGI 2. Another Windows server with Jenkins 3. Gitlab with Django application 4. Me :-) I am trying with psexec to run CMD file on host using Jenkins. Inside this file I has a simple script: cd "destination" git status git fetch --all git pull origin master On host server I have configured and generated SSH keys for my user account. Job has very simple configuration with only one build step as a batch script: PsExec64.exe \Remote_server script_path Django on host is cloned from SSH repository. When I try to run above script than I got "Access Denied" or some issues with git. But Jenkins doesn't produced any logs from git. Maybe I should set-up node on Host or use git remote url with HTTPS instead of SSH? -
git continues to control changes on __pycache__ even when it is in gitignore
This is my .gitignore: *__pycache__* *.pyc db.sqlite3 *.DS_Store media/ res/ I can see on my Atom that __pycache__ directories are VcsIgnored (which implies that are recognized as not version controlled by git) But, any way, when I make changes to a file, I get several __pycache__ files as modified and unstaged on my Atom git window: I don't know wether the problem is in git or in Atom. -
Django rest keep getting AssertionError: 'ListCreateAPIView' should either include a `queryset` attribute, or override the `get_queryset()` method
I'm building new app using Django rest and have this issue. I've searched on web, no solution or workaround was found. Here is the view.py code below of the serializer I've tried both overriding get_queryset() method and setting queryset variable, but no result views.py class GoodListCreateAPIView(ListCreateAPIView): authentication_classes = (authentication.BasicAuthentication, ) permission_classes = (permissions.IsAuthenticated, ) serializer_class = GoodModelSerializer queryset = Good.objects.all() I want to list all goods related to the user, but unfortunately there is an error.If you need some additional code or smth, just ask -
Heroku and Static IP for Touchnet
I am using python/django on heroku and need to post a form to a touchnet service using a static ip. I have looked at QuotaGuard static and Proximo but they don't seem to forward posted forms like that. Does anyone know how to accomplish this? -
Difference between using Django LocMemCache and Threading.local()?
in my Django app I need to be able to access and edit some shared information from multiple places in my application. This amount of information is small (a dictionary with strings and integers, rarely over 50 keys and usually < 10) and needs to be cleared/evicted after every request. Cost is crucial, so I'd rather not use an option like Memcached. The options I'm considering right now are using Django's built in locMemCache or using Python's built in Threading.local. I have tinkered with both options and they both seem to work in local development, why should I use/not use one or the other? Is there some meaningful advantage/disadvantage to one approach? Is one especially good/bad, ect ect ect?? Thanks. -
hwo to fix CSRF verification failed. Request aborted
i have a django website that include a form in order to submit data into the database. the problem is that one the user click the submit button the system display the below error : CSRF verification failed. Request aborted. yet i have include the csrf_token inside the form. form.py from django import forms from .models import contact class contactForm(forms.ModelForm): class Meta: model = contact fields = ( 'name', 'last_name', 'father_name', 'mother_name', 'gender', 'content', ) models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User # Create your models here. class contact(models.Model): MALE = 1 FEMALE = 2 GENDER = ( (MALE, 'Male'), (FEMALE, 'Female'), ) name = models.CharField(max_length=120) last_name = models.CharField(max_length=120) father_name = models.CharField(max_length=120) mother_name = models.CharField(max_length=120) gender = models.PositiveIntegerField(choices=GENDER,blank=True,null=True) content = models.TextField() create_date = models.DateTimeField(default=timezone.now,auto_now=False,auto_now_add=False) update_date = models.DateTimeField(default=timezone.now,auto_now=False,auto_now_add=False) user = models.ForeignKey(User,on_delete=models.CASCADE,default=1) html page <form method="POST" >{% csrf_token %} {{form.as_p}} <div id='left-column-Input' class="formInput" include="select()"> <div class="forminputs"> <input type="text" name="name" autocomplete="off" required /> <label for="name" class="label-name"> <span class="content-name" name="content-name">first name</span> </label></div> <div class="forminputs"> <input type="text" name="name" autocomplete="off" required /> <label for="name" class="label-name"> <span class="content-name" name="content-name">last name</span> </label></div> <div class="forminputs"> <input type="text" name="name" autocomplete="off" required /> <label for="name" class="label-name"> <span class="content-name" name="content-name">father name</span> </label></div> <button type="submit">Save</button> </form> and … -
Django (DRF): Per object field filter in REST API
Maybe I'm going about this the wrong way, but say I have a Post model (pseudo-code): class Post(models.Model): title = Charfield content = TextField scope = ChoiceField # same as status in UserProfile model and a UserProfile model: class UserProfile(models.Model): # other fields status = ChoiceField # same as scope in Post model Now, for members with a sufficient status, I want to return all posts regularly, with their title and content. However, for members with insufficient status, I do want to return the same QuerySet, but with the content field omitted from posts that require said scope. All other posts should be returned in full. Example: Post1: has "all" scope Post2: has "members only" scope User1: "all" scope User2: "member" scope Response: For User1: Post1 contains title and content, but Post2 contains only title. For User2: Post1 & Post2 both contain title and content. -
how to get context_object_name in django-tables2 view function? keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried (?P<pk>[0-9]+)$']?
when i try using the url 'appname:url_name' object.pk I get error that the app can't access the pk but when i try the same url in any view other than the tableview it works so i deduced that it can't access the 'object' to get the pk so how can I define it in the context to use it in the template. the table here has a button that triggers a modal and the modal has a form action with the wanted url. tables.py class Table(tables.Table): FirstName = tables.Column(linkify=("patients:patient_detail", {"pk": tables.A("pk")})) LastName = tables.Column(linkify=("patients:patient_detail", {"pk": tables.A("pk")})) Telephone_no = tables.Column(linkify=("patients:patient_detail", {"pk": tables.A("pk")})) delete = TemplateColumn('<button type ="button" class ="btn btn-danger" data-toggle="modal" data-target="#modalDelete" >Deleta</button>') class Meta: model = Entry attrs = {'class': 'table table-striped table-hover'} exclude = ("user", "Notes", "Adress") template_name = 'django_tables2/bootstrap4.html' Views.py def list(request): entrie = Entry.objects.all() table = Table(entries.filter(user=request.user)) RequestConfig(request).configure(table) return render(request, 'app_name/list.html',{ 'table' : table, 'object':entries, }) Template {% extends 'base.html' %} {% load render_table from django_tables2 %} {% block content %} <div id="content"> {% if user.is_authenticated %} {% render_table table %} {% else %} <h2>please login</h2> {% endif %} </div> <div class="modal fade" id="modalDelete" tabindex="-1" role="dialog" aria-labelledby="modalDelete" aria-hidden="true"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Delete object!</h5> <button type="button" … -
"UnicodeDecodeError: utf-8" trying to do "python manage.py runserver"
I've literally just started some Django lessons because I looked up the options I have and pretty sure it's the best way to complete an internship programming challenge a company assigned to me. The page I ran "django-admin startproject mysite" was "projetoEstados", then I went into mysite through prompt and tryied to run "python manage.py runserver", to be able to properly access 127.0.0.1:8000 and actually start the project, that's when I got the problem. I looked up on a few foruns, including StackOverflow, but couldn't find someone with the exact same problem I'm having, most people kinda knew where the problem was, I'm literally 1 hour into Django, so yes, I'm the most beginner someone could be, so I have no clue on where to go with that error message. So, the exact error I'm getting is in here. This print is unfortunately as specific as i can be, so please someone help me lol. I was obviously expecting no error message, maybe some unapplied migrations, but that's it. Don't know how obvious this information will be, but I can't access 127.0.0.1:8000 to access Django development server with that error happening. -
Django ORM - use SubQuery in FROM clause
Goal: Use RowNumber function to get number for each row, out of that, filter by a value, but retain the appropriate RowNumber given when not applying the filter, since otherwise RowNumber would always return 1. Before translating to Django ORM, I find it helps to get the SQL syntax, which is this: SELECT rn.row_number, name FROM ( SELECT ROW_NUMBER() OVER (ORDER BY name), name FROM customer ) as rn WHERE name = 'Juan' Problem I can´t manage to translate this to Django ORM. I have tried the following: subq = models.Customer.objects.all().annotate( rank=Window( expression=RowNumber(), order_by=(F('name')) ) ) Here´s where I don´t know how to continue. How do I tell my models.Customer to use subq as the FROM in its query? -
django establish correct relationships between models
I'm new to Django, trying to figure out how to set up my models so that I can accomplish my idea. On my web app, many passengers can book many flights via a form. I want to display all passengers that are associated with a particular flight. Example: London => Paris | [ "Bob", "Alice", "Bill" ] and I will then iterate though that list in my template. Sorry if this is too easy for you. I tried to get the individual flight by id in views.py and then displaying the data in the template: {{ london.passenger.name }} but it returns None views.py def flights(request): london = Flight.objects.get(id=1) context = {'london': london} return render(request, 'flights.html', context) models.py # Passenger model. class Passenger(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name # Flight model. class Flight(models.Model): origin = models.CharField(max_length=50) destination = models.CharField(max_length=50) duration = models.IntegerField(null=True, blank=True) passengers = models.ManyToManyField(Passenger) def __str__(self): return self.origin + " => " + self.destination -
usage of standard backward relation manager in serilizers
Question is about using standard Django backward related manager name in DRF. I have following serializer class ExtraUserSerializer(serializers.ModelSerializer): boatmodel_set = serializers.PrimaryKeyRelatedField(many=True, queryset=BoatModel.objects.all()) class Meta: model = get_user_model() fields = ("id", "username", 'boatmodel_set', ) This serializer represents primary model ExtraUser and boat_model set represents backward relationship to secondary model BoatModel. Related name “boatmodel_set” chosen simply because main core Django site uses this standard “secondarymodel_set” conventional backward related manager name so that in DRF part I had to use related_name = “ boatmodel_set” as well in order to not change code in the main part. Question is - is it possible to keep related_name = “ boatmodel_set” but represent it in rendered json as , for example “boats”?? Thank you -
Django ckeditor can not add youtube plugin
I have seen this tutorial https://samulinatri.com/blog/django-ckeditor-codesnippet-hightlightjs-youtube/ and I have downloaded the youtube plugin here https://ckeditor.com/cke4/addon/youtube Then I created the youtube folder and pushed it into it. Specifically my_project / static / ckeditor / ckeditor / plugins / youtube / After I python manage.py runserver, field ['content'] show normal, field ['content1'] it doesn't work (does not display frames textarea). Someone helped me check, I did something wrong. Thanks !!! File model.py class Posts(models.Model): title = models.CharField(max_length=50) content = RichTextUploadingField() content1 = RichTextUploadingField( config_name='special', extra_plugins=['youtube'], external_plugin_resources=[( 'youtube', '/static/ckeditor/ckeditor/plugins/youtube/youtube/', 'plugin.js', )], ) File setting.py CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'full', }, 'special': { 'toolbar': 'Special', 'toolbar_Special': [ ['Bold'], ['CodeSnippet', 'Youtube'], ], 'extraPlugins': ','.join(['codesnippet', 'youtube']), } } My_project ├── blog <= This my_app │ ├── view.py │ ├── form.py │ ├── model.py ├── project <= Project settings directory │ ├── __init__.py │ ├── settings.py <= settings │ ├── urls.py │ └── wsgi.py ├── static │ ├── ckeditor │ ├── ckeditor_uploader │ ├── ckeditor │ ├── plugins │ └── youtube │ └── youtube │ └── images │ └── lang │ └── plugin.js │ └── .... │ └── ... │ └── ... -
Post Request to Django Rest Api that has a filter. So messages/?room=4
My Backend is built like this. Every 'Room' has 'Messages' And Every Message has a Sender (person who sends it). I want to make a post request to messages/?room=4. So I want to basically add a message directly to the room with id=4. //models class UserProfile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: verbose_name_plural = 'All Users' def __str__(self): return self.user.username @receiver(post_save, sender=User) def create_user_data(sender, update_fields, created, instance, **kwargs): if created: user = instance profile = UserProfile.objects.create(user=user) class Message(models.Model): sender = models.ForeignKey(UserProfile, on_delete=models.CASCADE, related_name="sendermessage") content = models.CharField(max_length=500) date = models.DateField(default=date.today) canview = models.ManyToManyField(UserProfile, blank=True, related_name="messagecanview") class Meta: verbose_name_plural = 'Messages' def __str__(self): return "{sender}".format(sender=self.sender) class Room(models.Model): name = models.CharField(max_length=50) members = models.ManyToManyField(UserProfile, blank=True, related_name='room') messages = models.ManyToManyField(Message, blank=True, related_name='room') class Meta: verbose_name_plural = 'Rooms' def __str__(self): return "{name}".format(name=self.name) //serializers, views class UserProfileSerializer(serializers.ModelSerializer): username = serializers.CharField(source='user.username') class Meta: model = UserProfile fields = ('id', 'username') class MessageSerializer(serializers.ModelSerializer): sender_obj = UserProfileSerializer(source='sender', read_only=True) class Meta: model = Message fields = ('id', 'content', 'date', 'sender', 'sender_obj') class RoomSerializer(serializers.ModelSerializer): messages = MessageSerializer(many=True, read_only=True) members = UserProfileSerializer(many=True, read_only=True) class Meta: model = Room fields = ('id', 'name', 'members', 'messages') class UserProfileView(viewsets.ModelViewSet): http_method_names = ['get', 'post', 'put', 'delete', 'patch'] queryset = UserProfile.objects.all() serializer_class = UserProfileSerializer filter_backends = ( … -
What is the simplest way of receiving and then processing a csv on a website?
Essentially I built an application using Python (specifically Pandas) that reads a csv then performs some actions on it then ultimately produces an output graph. I wanted to make this application into a website and I have learnt a bit of HTML, CSS and JavaScript to do this. I want the website to mainly do these 2 things Receive a file Process the file using Python then output the image back to the website What is the best course of action for this problem? Learn Flask? Learn Django? Would I need to learn anything else? -
Signing up Multiple User types in Django
I am doing a project in which I have to deal with two types of users - company , students I have made 2 apps namely company and student to handle this. Now django does not support multiple types of users so i wanted to know the easiest way of doing it. I followed this Multiple User Types In Django but could not understand properly. I found people suggesting to use OnetoOneField for User and create a profile model separately for Company and Students and an option of creating profile ... class company_profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=50) location = models.CharField(max_length=100) email = models.EmailField() is_company = models.BooleanField(default = True) is_student = models.BooleanField(default = False) ... I tried creating models like this for the company and similarly for the student The problem is that if i allow creation of user first and then ask them to update their profile then It might happen that a student logs in place of the company before the company has updated its profile. I want to check the is_company or is_student attribute at the time of login. To do this I have followed several blogs / tutorials but kept on getting errors Can … -
Python DETAIL: Array value must start with "{" or dimension information
im trying to add a string to an ArrayField and I'm getting DETAIL: Array value must start with "{" or dimension information. error. this is how the model looks like the method update_credential is where im trying to add the merchant_id to merchants ArrayField. class CloverCredential(models.Model): tenant = models.OneToOneField('tenant.Tenant', unique=True, on_delete=models.CASCADE) token = EncryptedCharField(max_length=255, null=True) spreedly_receiver_token = EncryptedCharField(max_length=255, null=True) merchants = ArrayField(models.CharField(max_length=200, blank=True), null=True) def update_credential(self, new_token, merchant_id): self.token = new_token self.merchants = merchant_id self.save() This is the view where im calling update_credential and passing token and merchant_id class OAuthCallback(APIView): def api_request(self, path): return requests.get(path).json() def get(self, request, *args, **kwargs): code = request.GET.get('code', '') state = unsign_state(request.GET.get('state', '')) merchant_id = request.GET.get('merchant_id', '') tenant = get_object_or_404(Tenant, pk=state['tenant_id']) clover_credential, created = CloverCredential.objects.get_or_create(tenant=tenant) url = f'{settings.CLOVER_URL_US}/oauth/token?client_id={settings.CLOVER_APP_ID}&client_secret={settings.CLOVER_APP_SECRET}&code={code}' oauth_response = self.api_request(url) clover_credential.update_credential(oauth_response['access_token'], merchant_id) return redirect(state['redirect']) i also tried to append merchant_id to merchants self.merchants.append(merchant_id) and got this error AttributeError: 'NoneType' object has no attribute 'append' -
Django Rest Framework not retrieving data from my database
I'm creating an API endpoint to retrieve data from a Mongo database, in order to use it on my frontend. On my project, i'm using two DBs: a sqlite db and the Mongo DB. In the Mongo database, there is a collection called tst with some data in it. I created the endpoint, but after opening the api on my browser, i see no json data retrieved from the collection, as if it's not looking in the right place. Can someone help me find what i'm doing wrong? Here is my model: class tst(models.Model): id = models.CharField(max_length=100) ticker = models.FloatField() def save(self, *args, using=None, **kwargs): super(tst, self).save(*args, using='dbtwo', **kwargs) Here is my view: class tstList(generics.ListCreateAPIView): queryset = tst.objects.using('dbtwo').all() serializer_class = tstSerializer Here is the serializer: class tstSerializer(serializers.ModelSerializer): class Meta: model = tst fields = ('id', 'ticker', ) And the url: path('tst/', views.tstList.as_view()), -
Django - RawPostDataException: You cannot access body after reading from request's data stream
I'm really stuck at this problem for a couple of days now. While I understand, what's happening here, I don't really know the best workaround/solution for this. Problem: I'm trying to create a user login endpoint using Django and DRF in general. My login API needs to support a login via password as well as login via OTP. My LoginView looks like: def post(self, request, **kwargs): """ post Method to handle user login :param request: :param args: :param kwargs: :return: """ request_data = request.data login_using_password = request_data.get('login-with-password') is True login_using_otp = request_data.get('login-with-otp') is True if request_data is not None: if all((login_using_password, login_using_otp)): raise accounts_exceptions.InvalidLoginRequestError() if login_using_password: return Response(self._login_with_password(request)) elif login_using_otp: return Response(self._login_with_otp(request)) raise accounts_exceptions.InvalidLoginRequestError() return Response(self._login_with_password(request)) Also my _login_with_password looks like: def _login_with_password(self, request, **kwargs): """ _login_with_password A utility method to handle login with password :param request: :return: """ return getattr(ObtainJSONWebToken.as_view()(request=request._request, ), 'data') When I try to login, Django complains saying RawPostDataException You cannot access body after reading from request's data stream I'm using JWT to authenticate requests. ObtainJSONWebToken is a view provided by DRF-JWT to obtain access tokens to authenticate requests. What is the workaround/solution for this? Is there a better way to support such a login requirement? Thanks … -
How to merge existing Django project into a new one with custom user model?
I've researched this some but haven't yet found an easy way to do this. My current project uses the default User model, but I've realized I need to use a custom user model. Is there an easy way to build a new Django project with custom user model and then copy my existing project into it? I do not have a user base so I don't mind losing it.