Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting Pylint Error For No Reason: invalid syntax (<unknown>, line 59)
Trying to define a clear method for my shopping cart app. But I am getting this error for no reason. My code seems ok. This is where I am getting the error. On commenting this line, the error moves to the next line which is blank def clear(self): del self.session[settings.CART_SESSION_ID]self.session.modified = True The error is invalid syntax (<unknown>, line 59) My whole code: from django.conf import settings from ecom.models import Product class Cart(object): def __init__(self, request): self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: # save an empty cart in the session cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart def add(self, product, quantity=1, update_quantity=False): """ Add a product to the cart or update its quantity. """ product_id = str(product.id) if product_id not in self.cart: self.cart[product_id] = {'quantity': 0, 'price': str(product.price)} if update_quantity: self.cart[product_id]['quantity'] = quantity else: self.cart[product_id]['quantity'] += quantity self.save() def save(self): # update the session cart self.session[settings.CART_SESSION_ID] = self.cart # mark the session as "modified" to make sure it is saved self.session.modified = True def remove(self, product): product_id = str(product.id) if product_id in self.cart: del self.cart.session[product_id] self.save() #iterate over cart items and add them from database def __iter__(self): product_ids = self.cart.keys() products = Product.objects.filter(id__in=product_ids) for product in … -
Turn on webcam at client side and process the captured image(django)
I am working on a django web application and I want to add a function to scan barcode using webcam. I tried using openCv together with pyzbar to scan barcode but the problem is it only works on the localhost computer. Now i am trying to use html5 getUserMedia to capture the barcode image and send that image to django view function for processing. How can i write the view function and is there a way to detect and process the barcode right away from the webcam livestream using getUserMedia? video.onclick = function() { canvas.width = video.videoWidth; canvas.height = video.videoHeight; img.src = canvas.toDataURL('image/jpeg'); var source = img.src; $.ajax({ url: "{% url 'recordmgnts:barcode_scanner' %}", data: { 'image': source }, success: function(data){ $("#id_container_serial_number").attr("value",data); } }); }; from pyzbar import pyzbar import base64 def barcode_scanner(request): image = request.GET.get('image') #image sent from browser decode_image = base64.b64decode(image) barcode = pyzbar.decode(decode_image) barcode_data = barcode.data.decode("utf-8") return HttpResponse(barcode_data) -
How to create the one to many relationship based file upload using serialization
Only save the Project model fields doesn't create the project documents model fields Models.py class Project(BaseModel): name = models.CharField(max_length=100, blank=True, null=True) class Meta: db_table = 'project_details' ordering = ['is_active'] class ProjectDocuments(BaseModel): file = models.FileField(upload_to="files/%Y/%m/%d") project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='projectdocuments') class Meta: db_table = 'project_document_details' ordering = ['is_active'] views.py: def post(self, request, format=None): user_id = request.user.id current_date = datetime.now() data = copy.deepcopy(request.data) file_fields = list(request.FILES.values()) # list to be passed to the serializer data['is_active'] = True data['created_by'] = user_id data['created_date'] = current_date data['modified_by'] = user_id data['modified_date'] = current_date serializer = ProjectSerializer(data=data, file_fields=file_fields) if serializer.is_valid(): serializer.save() serializer.py: class ProjectSerializer(serializers.ModelSerializer): def init(self, *args, **kwargs): file_fields = kwargs.pop('file_fields', None) super(ProjectSerializer, self).__init__(*args, **kwargs) if file_fields: field_update_dict = {str(field): serializers.FileField(required=False, write_only=True) for field in file_fields} print "FILE UPDATE DICT ------------>",field_update_dict self.fields.update(**field_update_dict) def create(self, validated_data): validated_data_copy = validated_data.copy() validated_files = [] for key, value in validated_data_copy.items(): if isinstance(value, InMemoryUploadedFile): validated_files.append(value) validated_data.pop(key) submission_instance = super(ProjectSerializer, self).create(validated_data) for file in validated_files: ProjectDocuments.objects.create(submission=submission_instance, file=file) return submission_instance class Meta: model = Project fields = '__all__' -
Django intersection based on common field
I have chat and participant models. class Chat(models.Model): ... class Participant(models.Model): chat = models.ForeignKey(Chat, on_delete=models.CASCADE, related_name='participants') participant = models.ForeignKey(CustomUser, on_delete=models.CASCADE) ... I'm looking for a way to check if there exists a single chat with two specified users. I can think of doing an intersection of two separate querysets but am unsure how to combine them based on identical chat id. qs = Participant.objects.filter(participant=user_a).intersection(Participant.objects.filter(participant=user_b)) -
Django dev server not recognizing new files after directory modification
I have a Django project with 2 apps and was writing some functions in a utils.py file in one of the apps. I wanted to break this up into two separate files in their own subdirectory so I created a new directory 'utils' a level below the app directory and placed the two utils1.py and utils2.py files in there. I had some issues with importing something from the other app so I ended up scrapping this idea and moving everything back into one file in the base directory of the original app, exactly like it was before. Now when I runserver it is not picking up any new files that are created within apps. Not just the ones that I recreated but any new files. Files that were created prior to the change are running just fine. So, in summary new utils.py files that I recreated in the app directory are not running when the dev server is started, and when I try to run one of them manually they run like any other python file, but imports from other locations in the project are not being recognized. No other changes were made and new files were running perfectly fine … -
Integrating TinyMCE to Django
So i have been trying to use tinymce on my django project but i kept getting: ImportError: cannot import name 'TinyMCE' from 'tinymce' and Cannot find reference TinyMCE in init.py The very few articles online talks about integrating tinymce with django admin but i'm trying to integrate it with my django forms. pip installed django-tinymce ----settings.py---- INSTALLED_APPS = [ 'tinymce',] ----urls.py---- path('tinymce/', include('tinymce.urls')), ---models.py--- from tinymce.models import HTMLField container_description = HTMLField() ----forms.py---- from tinymce import TinyMCE class TinyMCEWidget(TinyMCE): def use_required_attribute(self, *args): return False class ContainerForm(forms.ModelForm): container_serial_number = forms.CharField(widget=forms.TextInput(attrs= {'placeholder': 'Enter serial number'})) container_description = forms.CharField(required=False, widget=TinyMCEWidget(attrs={'placeholder': 'Enter description'}), max_length=100) Followed instructions online for setting up but i still got ImportError. And what else am i supposed to do to set TinyMCE up? -
Django 4-way join
I'm trying to join tables in Django. These are my models: class Venture(models.Model): tug = models.ForeignKey(TugVessel, on_delete=models.CASCADE) start_port = models.ForeignKey(Port, on_delete=models.CASCADE, related_name='start') end_port = models.ForeignKey(Port, on_delete=models.CASCADE, related_name='end') # more fields class Port(models.Model): lat = models.DecimalField(max_digits=9, decimal_places=6) lon = models.DecimalField(max_digits=9, decimal_places=6) name = models.CharField(max_length=255) class UnmatchedRequest(models.Model): who = models.ForeignKey(CustomUser,on_delete=models.CASCADE) start_lat = models.DecimalField(max_digits=9, decimal_places=6) start_lon = models.DecimalField(max_digits=9, decimal_places=6) end_lat = models.DecimalField(max_digits=9, decimal_places=6) end_lon = models.DecimalField(max_digits=9, decimal_places=6) # more fields Now I want to get all the requests for a user, say where UnmatchedRequest.who = 1, then join twice with the Ports database so I can get the start port and end port, then use that to find a matching venture. I think the SQL query would be: SELECT * FROM Port P1, Port P2, UnmatchedRequest, Venture WHERE UnmatchedRequest=1 AND UnmatchedRequest.start_lat=P1.lat AND UnmatchedRequest.start_lon=P1.lon AND UnmatchedRequest.end_lat=P2.lat AND UnmatchedRequest.end_lon=P2.lon AND P1.id=Venture.start_port AND P2.id=Venture.end_port I was thinking something like this: UnmatchedRequest.objects.get(id=1).filter( start_lat=F('port__lat'), start_lon=F('port__lat'), end_lat=F('port__lat'), end_lon=F('port__lon'), port__id=F('Venture.start_port'), port__id=F('Venture.end_port') ) but I'm not clear on whether each of these ports refer to the same or different tables and I can't seem to find how I could alias them like in the SQL query to have one start port and one end port. Any ideas for how to implement … -
Django datetime strftime() return wrong timezone
I'm current trying to return a DateTimeField format by hour, minutes , second in the model: start = models.DateTimeField(auto_now_add=True) My settings.py: LANGUAGE_CODE = 'vi' TIME_ZONE = 'Asia/Saigon' USE_I18N = True USE_L10N = True USE_TZ = True When i try to format the DateTimeField current_ws.start.strftime('%H:%M:%S') # return 09:34:01 which is a wrong time , the correct should be 16:34:01 How do i fix this ? -
bad interpreter: Permission denied
I can not install psycopg2. I try to change the DB from sqlite to postgesql but get always the same error. I also tried to install it via the project interpreter instead of my terminal but get : python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. If you prefer to avoid building psycopg2 from source, please install the PyPI 'psycopg2-binary' package instead. (venv) localhost:mysite Sergio$ pip install psycopg2 bash: /Users/Sergio/PycharmProjects/#WE_GRAPPLE/venv/bin/pip: /Users/Sergio/PycharmProjects/#WE_GRAPPLE/venv/bin/python: bad interpreter: Permission denied (venv) localhost:mysite Sergio$ -
Best way to import data into Django
I am currently working on a project for scraping flight data from websites using python and storing that data in a database using Django. I was just wondering what is the best way to take the scraped data and import it into the Django models. thanks in advance for any help. -
How to fix 'TypeError: __init__() got an unexpected keyword argument 'sender''
I am trying to create a django model instance with a django-rest-framework serializer ModelSerializer class. This is my Serializer code: class MessageSerializer(serializers.ModelSerializer): class Meta: model = Message fields = ['sender', 'chat_room', 'content', 'sending_date'] and this is my view when I try to make a model instance out of it: message_serializer = MessageSerializer(sender=request.user, chat_room=ChatRoom.objects.get( id=request.data['chat_room_id']), content=MessageContent(text=request.data['text'])) message = Message(message_serializer.data) However, when I run this code, I get TypeError: init() got an unexpected keyword argument 'sender' If I delete the sender argument I get TypeError: init() got an unexpected keyword argument 'chat_room' and so on. I checked if my ModelSerializer was making the right serializer fields with print(repr(MessageSerializer())) in the django python shell, and I got MessageSerializer(): sender = PrimaryKeyRelatedField(queryset=User.objects.all()) chat_room = PrimaryKeyRelatedField(queryset=ChatRoom.objects.all()) content = PrimaryKeyRelatedField(queryset=MessageContent.objects.all(), validators=[<UniqueValidator(queryset=Message.objects.all())>]) sending_date = DateTimeField(read_only=True) which means that my serializer has these fields (sender, chat_room, etc.) Why do I get this error and how do I fix this? Thank you for your time! -
Not a valid regular expression
I cannot understand why i'm getting this error: django.core.exceptions.ImproperlyConfigured: "^customers/(?P<pk>[0-9]+)$" is not a valid regular expression: unknown extension ?P& at position 12 Here is my code of the file urls.py from django.conf.urls import url from customers import views urlpatterns = [ url(r'^customers/$', views.customer_list), url(r'^customers/(?P&lt;pk&gt;[0-9]+)$', views.customer_detail), url(r'^customers/age/(?P&lt;age&gt;[0-9]+)/$', views.customer_list_age), ] -
Django: Passing arguments to class-based view
I'm trying to pass arguments to a class-based view in Django. I've tried the various methods explained on this page but I can't get any of them to work. Django class-based view: How do I pass additional parameters to the as_view method? For example I've tried this but it doesn't work. url(r'^$', YourView.as_view(), {'slug': 'hello_world'}, name='page_name') I'm using Django 2.2.3 and I thought maybe things have changed since those answers were posted, but it still mentions this method in the Django docs: https://docs.djangoproject.com/en/dev/topics/http/urls/#passing-extra-options-to-view-functions So what am I doing wrong? -
django select_related Cannot resolve keyword
I'm trying to optimize my ORM queries in django. I use connection.queries to view the queries that django generate for me. Assuming I have these models: class Template_folder(models.Model): tf_id = models.AutoField(primary_key=True) tf_foldername = models.TextField(max_length=100) tf_parent = models.IntegerField() tf_seq = models.IntegerField() tf_sorter = models.TextField() class Meta: db_table = 'template_folder' class Templateforein(models.Model): tp_id = models.AutoField(primary_key=True) tp_idfolder = models.ForeignKey(Template_folder, to_field='tf_id', db_column='tp_idfolder') tp_title = models.TextField(max_length=45) tp_contents = models.TextField() tp_created = models.DateTimeField(default=timezone.now) tp_updated = models.DateTimeField(default=timezone.now) tp_iduser = models.IntegerField() class Meta: db_table = 'template' So should I use: template = Templateforein.objects.select_related().filter(Q(tf_id=tp_idfolder) | Q(tf_parent=tp_idfolder)) I have to use the template_folder model. Error content: django.core.exceptions.FieldError: Cannot resolve keyword 'tf_id' into field. Choices are: tp_choice, tp_confolderid, tp_contents, tp_created, tp_flowid, tp_id, tp_idfolder, tp_idfolder_id, tp_iduser, tp_pagenum, tp_title, tp_updated I think you should use the template model. I should use the template_folder model. How do I hang a filter with template_folder? -
Django button update DB and reloads the page
I'm fairly new to Django. I have a need for a button/s on my home page acknowledge the tasks and refresh it. Once acknowledged I need the status in my task model updated I don't have a variable to pass, it's home page it just needs to get refreshed. I tried with the path in url patterns but I need to pass a variable. And whenninpass on the variable I land on the individual task page. Is there a way I can call the views myfunction straight from html page to do the DB update? -
Reverse_lazy To URL Where Bootstrap Modal is Launched From
I have a page where the user can launch a bootstrap modal to update information on that page. I am using a class based update view to accomplish that within the modal. I would like for the user to submit on the modal form and then have them remain on the same page as where they originally launched the modal from. I am struggling to do this, because technically you're never leaving that page in the first place due to the modal - any help? The modal is launched from the 'manifest' url and I would like to reverse back to that after submission of the modal. urls.py url(r'^manifest$', manifest, name='manifest'), url(r'^manifest_update/(?P<pk>\d+)$', views.ManifestUpdate.as_view(), name='manifest_update'), views.py class ManifestUpdate(BSModalUpdateView): model = Manifests template_name = 'manifest_update.html' form_class = UpdateManifestForm success_message = 'Success: Manifest was updated.' success_url = reverse_lazy('manifest') When I do the above, the bootstrap modal simply doesn't submit, because as I mentioned I technically haven't navigated away from the 'manifest' url (or so I think). Not sure how I can make this happen successfully. -
Data not filling in with Edit Profile form Django
I'm using the following line to fill in data into the form. form = EditProfileForm(request.POST, instance=request.user) However, no data fills into the form. I just get the empty form. Not sure what's going wrong. I have a profile html where the data from each user shows up, but the line above is not working on the edit page. The model is the default user model. Django version 2.2.3. #views.py def editprofile(request): if request.method == 'POST': form = EditProfileForm(request.POST, instance=request.user) if form.is_valid(): agree = form.save(commit=False) agree.save() args = {'form': form} else: form = EditProfileForm(request.POST) args = {'form': form} return render(request, 'profile_edit.html', {'form':form}) Here is my forms.py: class EditProfileForm(UserChangeForm): username = forms.CharField(label='Username', widget=forms.TextInput(attrs={'class': "form-control"})) first_name = forms.CharField(label='First Name', widget=forms.TextInput(attrs={'class': "form-control"})) last_name = forms.CharField(label='Last Name', widget=forms.TextInput(attrs={'class': "form-control"})) email = forms.CharField(label= 'Email', widget=forms.EmailInput(attrs={'class': "form-control"})) class Meta: model = User fields = ['username', 'first_name', 'last_name', 'email', 'password'] def save(self, commit=True): user = super(EditProfileForm, self).save(commit=False) user.username = self.cleaned_data['username'] user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.email = self.cleaned_data['email'] if commit: user.save() return user -
How to chain select_related functions in Django?
I have the following tables in my database: class A(models.model): ... class B(models.model): a = models.ForeignKey(A) class C(models.model): b = models.ForeignKey(B) data = models.TextField(max_length=50) What I want to do is get the C object with a pk of 215, and select the related B object, and also select the related A object of the B object. Right now, what I am doing is this: c = Models.objects.select_related('b').select_related('a').get(pk=215) However, I get the following error: django.core.exceptions.FieldError: Invalid field name(s) given in select_related: 'a'. Choices are: b Is this possible to actually get all 3 objects with just one database hit? Thanks for any answers. -
In Django, is it better to store complex chaining save methods in models, or in views?
Lets say I have models similar to something like this: from django.db import models, transaction class X(models.Model): ... def do_something(self): ... class Y(models.Model): ... x = models.ForeignKey(X, on_delete=models.CASCADE) def do_something(self): ... def save(self, *args, **kwargs): super(Y, self).save(*args, **kwargs) self.x.do_something() self.x.save() class Z(models.Model): ... y = models.ForeignKey(Y, on_delete=models.CASCADE) def save(self, *args, **kwargs): super(Z, self).save(*args, **kwargs) self.y.do_something() self.y.save() In other words, if a Z object is saved, its referenced Y object is updated and saved, which in turn saves its referenced X object. Right now, as it clear from the code, the complex save process is stored entirely in the models module. In production, the save method of Z should be ideally made atomic. Anyway, my question is this: should this sort of logic be stored in views instead? Like there could be a view like so: @transaction.atomic def my_view(request, z_pk): z = Z.objects.select_related('y').select_related('x').get(pk=z_pk) z.save() y = z.y y.do_something() y.save() x = y.x x.do_something() x.save() ... Obviously, for the above scenario, the model module would be simplified into something like this: from django.db import models, transaction class X(models.Model): ... def do_something(self): ... class Y(models.Model): ... x = models.ForeignKey(X, on_delete=models.CASCADE) def do_something(self): ... class Z(models.Model): ... y = models.ForeignKey(Y, on_delete=models.CASCADE) Which one of … -
Where I should to put the "firebase_admin.initialize_app" command in a django application?
I'm a beginner in this field. My question is basically, where do I need to put the following code Like in the settings.py archive or views.py? I'm using it in the views.py but I'm not sure where. Do I need to create a new .py archive? Also, I'm trying to add some information to the cloud firestore. import firebase_admin from firebase_admin import auth, credentials, db from firebase_admin import firestore cred = credentials.ApplicationDefault() firebase_admin.initialize_app(cred, { 'projectId': 'xxxxx', }) db = firestore.client() -
No 'Access-Control-Allow-Origin' header on the requested resource in Django
I have read relevant question and understand what is cors. I followed each step. Install pip install django-cors-headers Add MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.cache.UpdateCacheMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'a9.core.access.middleware.AccessMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware', ] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True INSTALLED_APPS = ['corsheaders','otree'] And python3 manage.py migrate However, I still get the error: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.1 Is there something I am missing to make it work correctly? -
Django authentication failed with error 'csrf token missing or incorrect' when logon from cellphone
I implemented custom authentication in my django app. I was able tto logon from several different devices: desktop, cellphone, etc. The problem is if I have a logged in session running from desktop, I will get the CSRF verification failed error on my cell. But not the other way around. I I already logged on in my cell phone, I do not have any problem logging on from my PC. Here is my login view def login_page(request): form = LoginForm(request.POST or None) context = { "form": form, 'namespace':'accounts', } next_ = request.GET.get('next') next_post = request.POST.get('next') redirect_path = next_ or next_post or None # if redirect_path == '/': redirect_path = '/dashboard/' if form.is_valid(): username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") user = authenticate(request, username=username, password=password) if user is not None: if user.is_active: login(request, user) try: del request.session['guest_email_id'] except: pass if is_safe_url(redirect_path, request.get_host()): return redirect(redirect_path) else: return redirect("/") # return redirect("dashboard/") else: # Return an 'invalid login' error message. print("LOGIN FAIL: Someone is trying to login and failed!") print("LOGIN FAIL: Username: {} and password: {}".format(username, password)) return HttpResponse("invalid username or password") else: return render(request, "accounts/login.html", context) -
How to form a queryset from two fields(columns) of the same model(same object)?
I'm trying to form a query set to load into a select form. This queryset has values that come from 2 fields of the same model(same object) from another model. For example, I have a GameId(object) stored in my database with a slug = 1sunariatl. This game id has GameId.home = ari and GameId.visitor = atl. I want to create a new form (PlayForm) with a select field(driving) that lets the user choose between the home team and the visitor team. (Select field in form will show "atl" and "ari") How do I form a new queryset based on these specific field values of the same object? models.py class GameId(models.Model): week = models.CharField(max_length = 100) day = models.CharField(max_length = 100) home = models.ForeignKey(Team, on_delete=models.SET_NULL, null = True, related_name='home') visitor = models.ForeignKey(Team, on_delete=models.SET_NULL, null = True, related_name='visitor') class Play(models.Model): driving = models.CharField(max_length = 100) forms.py class GameIdForm(forms.ModelForm): class Meta: model = GameId fields = [ 'day', 'week','home', 'visitor' ] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['home'].queryset = Team.objects.all() class PlayForm(forms.ModelForm): def __init__(self, round_list, *args, **kwargs): super(PlayForm, self).__init__(*args, **kwargs) self.fields['driving'].queryset = #insert code here class Meta: model = Play fields = [ 'driving' ] -
Is auth customization secure in django?
I've extended user model with o2o relationship model (UserProfile). I want to make logging in with email/password instead of username/password. So I customized the auth backend. Is logging in vulnerable with that way of authentication? from django.contrib.auth import get_user_model from django.contrib.auth.backends import ModelBackend class EmAuth(ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): UserModel = get_user_model() try: user = UserModel.objects.get(email=username) except UserModel.DoesNotExist: return None else: if user.check_password(password): return user return None def get_user(self, user_id): UserModel = get_user_model() try: return UserModel.objects.get(pk=user_id) except UserModel.DoesNotExist: return None -
Problems with saving and showing data with using from multiple checkboxes
Oay, let's start from the beginning ... I create a blog in Django. And I want to create something like a "playlist" containing several related posts (I hope you will understand) . But I have problem because I don't know how to display all posts in this "playlist". What is more I don't even know if I save all data in correct way, so if something is wrong please help. models.py: class Queue(models.Model): title = models.CharField(max_length=200, unique=True) description = models.TextField(max_length=500, default="Brak opisu") date_created = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ManyToManyField(Post) def __str__(self): return self.title forms.py: class QueueForm(BSModalForm): post = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=((x.id, x.title) for x in Post.objects.all())) class Meta: model = Queue fields = ['title', 'description', 'post'] views.py: class QueueCreateView(BSModalCreateView, LoginRequiredMixin): template_name = 'blog/queue_form.html' form_class = QueueForm def form_valid(self, form, **kwargs): form.instance.author = self.request.user return super().form_valid(form) def get_success_url(self): reverse_user = self.request.user return reverse('profile', kwargs={'username': reverse_user}) html file: {% for queue in queues %} {{queue.title}} {{queue.post}} {% endfor %}