Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to fix Jenkins error. no such table: users_user
Not sure where to start. I just want Jenkins to run tests via python manage.py test In my build step I am run migrtaions after installing necessary packages. Output: [...] Applying auth.0012_alter_user_first_name_max_length... OK Applying users.0001_initial... OK Applying admin.0001_initial... OK [...] Part of Traceback (starting @ test command): + python manage.py test /var/lib/jenkins/shiningpanda/jobs/1d61c5c6/virtualenvs/d41d8cd9/lib/python3.8/site-packages/environ/environ.py:628: UserWarning: /var/lib/jenkins/workspace/New_Performance_Realm/speedrealm/.env doesn't exist - if you're not configuring your environment separately, create one. warnings.warn( Creating test database for alias 'default'... Traceback (most recent call last): File "/var/lib/jenkins/shiningpanda/jobs/1d61c5c6/virtualenvs/d41d8cd9/lib/python3.8/site-packages/django/db/backends/utils.py", line 82, in _execute return self.cursor.execute(sql) File "/var/lib/jenkins/shiningpanda/jobs/1d61c5c6/virtualenvs/d41d8cd9/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 421, in execute return Database.Cursor.execute(self, query) sqlite3.OperationalError: no such table: users_user The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/var/lib/jenkins/shiningpanda/jobs/1d61c5c6/virtualenvs/d41d8cd9/lib/python3.8/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/var/lib/jenkins/shiningpanda/jobs/1d61c5c6/virtualenvs/d41d8cd9/lib/python3.8/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/var/lib/jenkins/shiningpanda/jobs/1d61c5c6/virtualenvs/d41d8cd9/lib/python3.8/site-packages/django/core/management/commands/test.py", line 23, in run_from_argv super().run_from_argv(argv) File "/var/lib/jenkins/shiningpanda/jobs/1d61c5c6/virtualenvs/d41d8cd9/lib/python3.8/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/var/lib/jenkins/shiningpanda/jobs/1d61c5c6/virtualenvs/d41d8cd9/lib/python3.8/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/var/lib/jenkins/shiningpanda/jobs/1d61c5c6/virtualenvs/d41d8cd9/lib/python3.8/site-packages/django/core/management/commands/test.py", line 55, in handle failures = test_runner.run_tests(test_labels) File "/var/lib/jenkins/shiningpanda/jobs/1d61c5c6/virtualenvs/d41d8cd9/lib/python3.8/site-packages/django/test/runner.py", line 725, in run_tests old_config = self.setup_databases(aliases=databases) File "/var/lib/jenkins/shiningpanda/jobs/1d61c5c6/virtualenvs/d41d8cd9/lib/python3.8/site-packages/django/test/runner.py", line 643, in setup_databases return _setup_databases( File "/var/lib/jenkins/shiningpanda/jobs/1d61c5c6/virtualenvs/d41d8cd9/lib/python3.8/site-packages/django/test/utils.py", line 179, in … -
What else can I try to debug a "ModuleNotFoundError" in Django?
I’m having problems with one module in my Visual Studio Core project. It is not being found. It generates this error: File "C:\Users\danj\source\repos\project_django\comstockapt\comstockapt\urls.py", line 28, in from comstockapt.email_accounts import views as email_views ModuleNotFoundError: No module named 'comstockapt.email_accounts' I’ve gone through many, many similar questions, but I can’t get it to work. I’m using the virtual environment. When I execute “python” in the terminal and then run ‘help(“modules email_accounts”)’ it shows the module with all of its files. When I run help(“modules”), I see all of my modules listed in the response. Here is my urls.py file within module comstockapt.comstockapt. Here is my installed_apps: I've checked environment variables, the virtual environment, the directory structure. What can I try next? -
Partial updating a ManyToMany field, but keeping its get representation
I've been scratching my head about this problem for a couple of hours now. Basically, I have two models: User and Project: class User(AbstractUser): username = None email = models.EmailField("Email Address", unique=True) avatar = models.ImageField(upload_to="avatars", default="avatars/no_avatar.png") first_name = models.CharField("First name", max_length=50) last_name = models.CharField("Last name", max_length=50) objects = UserManager() USERNAME_FIELD = "email" class Project(models.Model): name = models.CharField("Name", max_length=8, unique=True) status = models.CharField( "Status", max_length=1, choices=[("O", "Open"), ("C", "Closed")], default="O", ) description = models.CharField("Description", max_length=3000, default="") owner = models.ForeignKey( User, on_delete=models.SET_NULL, null=True, related_name="project_owner" ) participants = models.ManyToManyField(User, related_name="project_participants", blank=True) created_at = models.DateTimeField(auto_now_add=True) I use standard ModelViewSets for both of them, nothing changed. Then there's my Project serializer: class ProjectSerializer(serializers.ModelSerializer): class Meta: model = Project fields = "__all__" status = serializers.CharField(source="get_status_display", required=False) owner = UserSerializer() participants = UserSerializer(many=True) I use UserSerializers here, because having them achieved first of my two goals: I wanted to get the user data when getting the project from the API -> owner is a serialized User with all the fields, same for participants, but it's a list of users I want to be able to partially update the Project, for example add a participant So I searched through the docs and SO and I always found answers … -
Filter in Django array
How do I filter an array with a property from a model? class InvestorCountry(SimpleListFilter): """ This filter is being used in django admin panel in Investor model. """ title = 'Country' parameter_name = 'profile__country' def lookups(self, request, model_admin): return ( ('US', 'US'), ('non_US', 'non-US') ) def queryset(self, request, queryset): print("First::", queryset[0].investor_country()) print("Second::", queryset.filter(profile__country__exact='US')) print("Third::", queryset.filter(profile__country=['US'])) if self.value() == 'US': return queryset.filter(profile__country=['US']) The print shows this: First :: US Second :: <QuerySet [<Investment: Prosy Arceno>, <Investment: Prosy Arceno>, <Investment: Prosy Arceno>]> Third :: <QuerySet []> these are the data: I think this is the closest I've ever gone since I asked this question, but I still can't figure out how to filter based on a property. Can anyone help? -
Checking if user exists and using its data if it does
I have a view in which the user has to fill either the email or phone fields and then choose a pizza from an items list. The thing is, if the user enters an email or a phone then I need to check if the email or phone match an existing user (if it does, then the order uses that one, if not then no user is used). But if the user enters both fields and the user exists then I use that one and, if not, I create it. Since I'm doing all of this through a view that connects to the order serializer that is connected to the order model, I am not sure how I can implement this, since the user's data is connected to its own serializer and model. I am new to this type of thing so any advice on how to tackle this would be very appreciated. I wrote something in my view that does not work but should illustrate what I mean... maybe there's a way to do it like that but make it work? These are the models: class Client(models.Model): email = models.EmailField(max_length=200) phone = models.IntegerField() def __str__(self): return self.email class Order(models.Model): … -
Django, template. Can't pass variable inside if statement
I am using django all auth to sign in with my Google accounts. I'm able to get {userName} to display on the template. I also created a table and pass {userName} as a hidden field. When I try to match {userName} to match the table's userName in my if statement to only display certain rows of data, nothing shows up. I can't get {userName} directly in my view and pass it on to my template because django all auth uses different views. -
Passing authenticated_user kwargs to Django Form with Class-based View
I have a Django application to track referrals (referred by a user). I want to pass the id of the authenticated user to the ModelForm 'referrer' field (and since it's from the current logged in user the field shouldn't be editable). class Referral(models.Model): name = models.CharField(max_length=100) referrer = models.ForeignKey('users.User', on_delete=models.SET_NULL, related_name='referrals', null=True, blank=True) View: class ReferralFormView(FormView): form_class = ReferralForm template_name = "refer.html" success_url = reverse_lazy('thanks') def get(self, request): if request.user.is_authenticated(): return super(ReferralFormView, self).get(request) else: return redirect('login') def get_form_kwargs(self): user = self.request.user form_kwargs = super(ReferralFormView, self).get_form_kwargs() form_kwargs['referrer'] = user.id return form_kwargs def form_valid(self,form): ... form.save() return super(ReferralFormView, self).form_valid(form) I override get_form_kwargs in the view, then modify form init class ReferralForm(forms.ModelForm): class Meta: model = Referral def __init__(self, *args, **kwargs): referrer = kwargs.pop('referrer', None) super(ReferralForm, self).__init__(*args, **kwargs) self.fields['referrer'].disabled = True self.fields['referrer'].queryset = User.objects.filter(id=referrer) However all I see is a blank referrer field, what am I missing to pass the user id to that field? thanks -
Parse Nested Url Encoded Data from POST Request
I am creating a callback URL in Django for a webhook in Mailchimp. Mailchimp sends a POST request to the URL whenever certain actions are performed on users in Mailchimp. These POST requests contain data in the body in the form application/x-www-form-urlencoded. Mailchimp does not provide an option to choose the format of the data returned, so we must use the URL-encoded data. Now, the issue is that the data returned contains nested data. That is, lists and dictionaries (or JSON, since it is an HTTP request), are in the url-encoded data. For example, one POST request from Mailchimp, which is sent when a user changes their name, would look like: type=profile&fired_at=2021-05-25+18%3A03%3A23&data%5Bid%5D=abcd1234&data%5Bemail%5D=test%40domain.com&data%5Bemail_type%5D=html&data%5Bip_opt%5D=0.0.0.0&data%5Bweb_id%5D=1234&data%5Bmerges%5D%5BEMAIL%5D=test%40domain.com&data%5Bmerges%5D%5BFNAME%5D=first_name&data%5Bmerges%5D%5BLNAME%5D=last_name&data%5Blist_id%5D=5678 Using Django's request.POST, the data is decoded into: type=profile&fired_at=2021-05-25 18:03:23&data[id]=abcd1234&data[email]=test@domain.com&data[email_type]=html&data[ip_opt]=0.0.0.0&data[web_id]=1234&data[merges][EMAIL]=test@domain.com&data[merges][FNAME]=first_name&data[merges][LNAME]=last_name&data[list_id]=5678 This is less than optimal, since to access the first name of the user from this data we would have to write request.POST.get("data['merges']['FNAME']", None) when the data is intended to be accessed more like data = request.POST.get('data', None) try: first_name = data['merges']['FNAME'] except KeyError: first_name = '' I have looked for a Django/Python specific way to decode this nested URL-encoded data into more appropriate formats to work with it in Python, but have been unable to find anything. … -
Logstash Error: "too many arguments" when attempting to start/run logstash
Was attempting to run logstash on my python/django project with the following command on windows (using git bash): ./logstash -f path/to/logstash.conf I was getting this error /c/Program Files/logstash-7.13.0/bin/logstash: line 40: cd: too many arguments /c/Program Files/logstash-7.13.0/bin/logstash: line 40: /c/Users/Stephanie/Documents/Projects/BidRL/bidrl-reporting/bin/logstash.lib.sh: No such file or directory /c/Program Files/logstash-7.13.0/bin/logstash: line 41: setup: command not found /c/Program Files/logstash-7.13.0/bin/logstash: line 59: setup_classpath: command not found /c/Program Files/logstash-7.13.0/bin/logstash: line 60: exec: : not found I created a notion with every step I took to try to resolve the error. Eventually I decided to try moving logstash from c/program files to c. This solved the issue. I cd into the logstash directory: cd "/c/logstash-7.13.0/bin/" And then run logstash ./logstash -f path/to/logstash.conf This is the output Using bundled JDK: /c/logstash-7.13.0/jdk OpenJDK 64-Bit Server VM warning: Option UseConcMarkSweepGC was deprecated in version 9.0 and will likely be removed in a future release. WARNING: Could not find logstash.yml which is typically located in $LS_HOME/config or /etc/logstash. You can specify the path using --path.settings. Continuing using the defaults Could not find log4j2 configuration at path /C:/Program Files/logstash-7.13.0/config/log4j2.properties. Using default config which logs errors to the console [INFO ] 2021-05-25 14:34:41.276 [main] runner - Starting Logstash {"logstash.version"=>"7.13.0", "jruby.version"=>"jruby 9.2.16.0 (2.5.7) 2021-03-03 f82228dc32 … -
ImproperlyConfigured: Error finding Upload-Folder. Maybe it does not exist?
I found a Django project and failed to upload files to it. git clone git clone https://github.com/NAL-i5K/django-blast.git $ cat requirements.txt in this files the below dependencies had to be updated: psycopg2==2.8.6 I have the following Dockerfile: FROM python:2 ENV PYTHONUNBUFFERED=1 RUN apt-get update && apt-get install -y postgresql-client WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ RUN mkdir -p /var/log/django RUN mkdir -p /var/log/i5k For docker-compose.yml I use: version: "3" services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data - ./scripts/install-extensions.sql:/docker-entrypoint-initdb.d/install-extensions.sql environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db links: - db $ cat scripts/install-extensions.sql CREATE EXTENSION hstore; I had to change: $ vim i5k/settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db', 'PORT': '5432', } } #https://github.com/NAL-i5K/django-blast/blob/master/i5k/settings.py#L223 ... FILEBROWSER_SUIT_TEMPLATE = True FILEBROWSER_DIRECTORY = '' FILEBROWSER_VERSIONS_BASEDIR = '_versions/' FILEBROWSER_MAX_UPLOAD_SIZE = 10737418240 # 10GB FILEBROWSER_EXTENSIONS = { 'Folder': [''], #'Image': ['.jpg', '.jpeg', '.gif', '.png', '.tif', '.tiff'], 'Document': ['.pdf', '.doc', '.rtf', '.txt', '.xls', '.csv', '.docx'], #'Video': ['.mov', '.wmv', '.mpeg', '.mpg', '.avi', '.rm'], #'Audio': ['.mp3', '.mp4', '.wav', '.aiff', '.midi', '.m4p'], 'FASTA': ['.fa', '.faa', '.fna', '.fasta', '.cds', '.pep'], … -
ModuleNotFoundError: No module named 'psycopg2' error: python3, django, settings.py?
First of all, I've read I think all the most recent (2019 onwards) posts here about this problem to no avail :( I've got an up&running default webapp with python3 and django already working with default db.sqlite2. I now neeed to change all that db backend to psql. So, from these sources: https://pypi.org/project/psycopg2/ https://www.psycopg.org/docs/install.html I've installed psycopg2-binary, OK. From this source: https://www.enterprisedb.com/postgres-tutorials/how-use-postgresql-django I've modified settings.py, DATABASES section, to use psql instead of sqlite. I've tried: 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'ENGINE': 'django.db.backends.postgresql', And both gives me the error: (env) PS D:\Users\llagos.NB-KEYONE15\Visual Studio projects\ecommerce-psql> python manage.py makemigrations Traceback (most recent call last): File "D:\Users\llagos.NB-KEYONE15\Visual Studio projects\ecommerce-psql\env\lib\site-packages\django\db\backends\postgresql\base.py", line 25, in <module> import psycopg2 as Database ModuleNotFoundError: No module named 'psycopg2' ... django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named 'psycopg2' So, what's wrong with this settings.py file? is this correct? I've tried to google for information but again, no luck. Documentation for psycopg2 doesn't say what to change on settings.py. It just say "install and code", but when using django, there are previous steps, like this settings.py file. Thanks a lot for any hint! Regards, -
Django changing model value based on relationship with other model
I'm working on a project that has three models, one of which has a value that is dependent on if the other two are linked to it by a foreign key. the value can also switch if the links change. I was wondering how I would go about that. For example: general/models.py class Person(models.Model): DEFAULT = 'D' A = 'A' B = 'B' BOTH = 'AB' TYPES = [ (DEFAULT,'Default'), (A,'Type A'), (B,'Type B'), (BOTH,'Type A & B') ] # type is default if Person is not linked to A or B # A if Person is linked to A # B if Person is linked to B # BOTH if Person is linked to both type = models.CharField(max_length=2, choices=TYPES, default=DEFAULT) A/models.py class A(models.Model): person = models.ForeignKey('general.Person',on_delete=models.CASCADE) B/models.py class B(models.Model): person = models.ForeignKey('general.Person',on_delete=models.CASCADE) -
GLTF file is loading but it displaying black in browser three.js
I am working on my project in Django where I am using three.js to load my model and animate it I was able to load my .gltf file but it getting displayed black on my browser my website background color is white even though it's showing the black screen.I am totally new to the Three.js pls guide me here is my code <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="{% static 'mysite/style.css' %}" type="text/css"> <script src="https://ajax.googleapis.com/ajax/libs/threejs/r76/three.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/92/three.min.js"></script> <script src="https://cdn.jsdelivr.net/gh/mrdoob/three.js@r92/examples/js/loaders/GLTFLoader.js"></script> <script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script> <!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/100/three.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/100/three.min.js"></script>--> <title>Finance Assistant</title> </head> <body> <canvas class="webgl"></canvas> <script type="text/javascript"> // Debug //const gui = new dat.GUI() const gltfloader = new THREE.GLTFLoader(); // Canvas const canvas = document.querySelector('canvas.webgl') // Scene const scene = new THREE.Scene() //Hand gltfloader.load("{% static 'mysite/HomeHand.gltf' %}", function(gltf) { scene.add(gltf.scene); }); /* Objects const geometry = new THREE.TorusGeometry( .7, .2, 16, 100 ); // Materials const material = new THREE.MeshBasicMaterial() material.color = new THREE.Color(0xff0000) // Mesh const sphere = new THREE.Mesh(geometry,material) scene.add(sphere) */ // Lights const pointLight = new THREE.PointLight(0xffffff, 0.1) pointLight.position.x = 2 pointLight.position.y = 3 pointLight.position.z = 4 scene.add(pointLight) /** * Sizes */ const sizes = { width: window.innerWidth, height: window.innerHeight } window.addEventListener('resize', … -
Save the changes into user log of two different field separately
I am using Django where I'm trying to show to users any changes in the table made by the user itselfs. Something like a user log. So any data changes inside the system will be displayed in User Log. The current issue is so far I can manage to capture the changes for only one field in the table. But it is needed to get any changes in several fields. def updatePart(request, pk): action = 'update' part = Part.objects.get(id=pk) previous_standard = part.standardpack previous_pack = part.stylepack form = PartForm(instance=part) if request.method == 'POST': form = PartForm(request.POST, instance=part) if form.is_valid(): pack= form.save() create_log(request, pack, object_repr=pack.partname, change_message=f"stylepack {previous_pack} to {pack.stylepack}") create_log(request, pack, object_repr=pack.partname, change_message=f"standardpack {previous_standard} to {pack.standardpack}") return redirect('part-list') context = {'action': action, 'form': form} return render(request, 'store/update_part.html', context) Here is the part table, there are nine fields here that I'd like to save the changes in userlog. Base on the current situation, if only "stylepack" field data changes, the user log show this at the same time Changed “Outer Opening Handle Assy Door RH RL (C/BROWN)” — Standardpack 17 To 17 Changed “Outer Opening Handle Assy Door RH RL (C/BROWN)” — Stylepack Rack2 To Rack How can I solve this issue that … -
How can I present the option to create a new related model instance alongside existing options presented in a Django form from a ManyToMany field?
I am building an auction website a la eBay, and want to, when adding a new listing, be able to associate 0 or more categories with that listing. Specifically I would like a Categories CheckboxSelectMultiple (or similar?) that: Lists all existing categories as options Presents an option to create a new category which, when selected, presents a CharField, the value of which will be saved as the title of a new category, and that category and the new listing associated with each other. I have the following m2m relationship set up in models.py: class Category(models.Model): name = models.CharField(max_length=64) class Listing(models.Model): categories = models.ManyToManyField(Category, blank=True) ... and, on GET request, am passing the following ModelForm from forms.py to my new_listing.html template: class ListingForm(ModelForm): class Meta: model = Listing widgets = {'categories': forms.CheckboxSelectMultiple} fields = ['title', 'categories','starting_price', 'image_url', 'description'] I am having trouble figuring out how to do this, any help is much appreciated! -
Creating multiple url_paths for a Django actions-based view
I am using DRF and I have this viewset action view: @action(methods=['get'], detail=False, url_path=r'top-products/(?P<tag>\w*)/(?P<query>\w*)') def top_products(self, request, tag='', query=''): print(f'tag \t {tag}, query \t {query}') filtered = Product.objects.all() \ .annotate(items_count=Count('products_users')) \ .order_by('-items_count') if tag: filtered.filter(tags__name=tag) if query: filtered.filter(name__contains=[query.lower()]) topProducts = filtered paginator = StandardResultsSetPagination() result_page = paginator.paginate_queryset(topProducts, request) data = ProductSerializer(result_page, many=True).data return paginator.get_paginated_response(data) It is filtering the top products based on a query and a tag if they exist. Now as I want to make the function generic that works for three cases: - tag and query values exist - one of them exists - none exist After a bit of search I found that I needed to create one URL pattern for each case, but how can we do multiple url paths for an action view in Django? -
django did replace the existing name with new name because of the same name not other field. help appricated
I have an inquiry form and when I try to give data as below. ram, 20, surket, usa ram, 22, diren, usa unable to get stored in database 1 might get replaced. help appreciated tried numerous research but failed. I want to store both values in the database. would you let me know what to use? -
Can I access an elements index within a dictionary value?
I am passing a dictionary with one Key, Value pair where the value is a list of images. Is there any way to only loop through the first 4 elements within the values list? Here is my views.py file: def portfolio_couples(request): img_list = os.listdir("/Users/andershanson/Documents/Django/kh_photo/static/my_app/images/portfolio") context = {"images": img_list} return render(request, 'my_app/couples.html', context) Here is my HTML template: {% if images %} {% for image in images %} <img src="/static/my_app/images/portfolio/{{ image }}" class="container-fluid px-0 m-0" alt="portfolio-pic"> {% endfor %} {% endif %} This currently works looping through images, but is there any way to index the the first 4 elements in the dictionary value?? Thanks! -
how to insert a python variable inside a hyperlink in html using Django?
In this html block: {% block body %} <h1>All Pages</h1> <ul> {% for x in entries %} {% comment %} {% wik = 'mask/' + x + '.md' %} {% endcomment %} <li><a href = 'mask/'{{x}} </a>{{ x }}</li> {% endfor %} </ul> {% endblock %} I am trying to insert a string in x that will go to end of the hypertext. mask/cat, where "cat" is x [just as an example]. When I do this, the entry does not seem to be added to the hyperlink when I click it. The other way I thought is to create a python variable wik with the correct page hyperlink, but then I get an issue in Django Invalid block tag on line 12: 'wik', expected 'empty' or 'endfor'. Did you forget to register or load this tag? Any help appreciated thanks -
update object if exists and create if it not exists django
i'm trying to create new object if not exists and update some fields if it exists , i've seen several answers but still its unclear , and i couldnt implement it well this is my models.py class Information(models.Model): name = models.CharField(max_length=50,unique=True) def __str__(self): return self.name class Item(models.Model): item = models.ForeignKey(Information,on_delete=models.CASCADE) quantity = models.IntegerField() quantity_storage = models.IntegerField(blank=True) buying_price = models.DecimalField(max_digits=30,decimal_places=3) def __str__(self): return self.item.name def save(self,*args,**kwargs): if self.item: Item.objects.filter(item__name=self.item).update( quantity=F('quantity') + self.quantity else: super(Item,self).save(*args,**kwargs) i have to update quantity field if the object already exists for example i've entered item :cableXYZ , quantity : 10 then i enter cableXYZ again with quantity : 20 it should update the quantity field to 30this works fine , but when i try to enter a new object which doesnt exists , it wont save the object ! is there something i've missed to add to save save() method ?! or isnt there a better approach to achieve it please ?! i very appreciate your helps -
How can I insert the try except block in this django-import-export view?
I can't get it right on how to appropriately add a try except block in this django-import-export view. My aim is to catch and display the particular errors that might be experienced during import. I believe a try except block can help but I don't know how to implement it in this view. class upload(LoginRequiredMixin,View): context = {} def post(self, request): form = UploadForm(request.POST , request.FILES) data_set = Dataset() if form.is_valid(): file = request.FILES['file'] extension = file.name.split(".")[-1].lower() if extension == 'csv': data = data_set.load(file.read().decode('utf-8'), format=extension) else: data = data_set.load(file.read(), format=extension) resource = ImportResource() result = resource.import_data(data_set, dry_run=True, collect_failed_rows=True, raise_errors=True) if result.has_validation_errors() or result.has_errors(): messages.success(request,result.invalid_rows) self.context['result'] = result return redirect('/') else: result = resource.import_data(data_set, dry_run=False, raise_errors=False) self.context['result'] = None messages.success(request,f'Successfully.') else: self.context['form'] = UploadForm() return render(request, 'home.html', self.context) -
docker-compose run app python manage.py migrate results in psycopg2: database "app" does not exist
I have a Django app with Docker,I added postgres image and made all settings to create postgres db, but when I run "docker-compose up" which contains command: sh -c "python manage.py wait_for_db && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" it fails when it comes to migrate docker-compose.yml: version: "3" services: app: build: context: . ports: - "8000:8000" volumes: - ./app:/app command: > sh -c "python manage.py wait_for_db && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" environment: - DB_HOST=db - DB_NAME=app - DB_USER=postgres - DB_PASS=supersecretpassword depends_on: - db db: image: postgres:10-alpine environment: - POSTRGES_DB=app - POSTGRES_USER=postgres - POSTGRES_PASSWORD=supersecretpassword Dockerfile: FROM python:3.7-alpine MAINTAINER kubousky ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /requirements.txt RUN apk add --update --no-cache postgresql-client RUN apk add --update --no-cache --virtual .tmp-build-deps gcc libc-dev linux-headers postgresql-dev RUN pip install -r /requirements.txt RUN apk del .tmp-build-deps RUN mkdir /app WORKDIR /app COPY ./app /app RUN adduser -D user USER user settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'HOST': os.environ.get('DB_HOST'), 'NAME': os.environ.get('DB_NAME'), 'USER': os.environ.get('DB_USER'), 'PASSWORD': os.environ.get('DB_PASS'), } } The first part of command: **python manage.py wait_for_db** && python manage.py migrate && python manage.py runserver 0.0.0.0:8000 is OK because of the message "Database available!!!". docker-compose run app python manage.py migrate … -
"NameError: name '_mysql' is not defined" error happening on Django only when running as ./manage.py
I'm working on a django project on MacOS 11.3 Intel. Problem is when I run "./manage.py runserver" I get error "NameError: name '_mysql' is not defined", however when running "python manage.py runserver" project starts whitout a problem. In trying to use vscode debugger I realized it jumpstarts the project with "./manage.py runserver" so I get the error and can't debug. I use Poetry as my package manager and have already added to my .zshrc file, the following commands: "export PATH=${PATH}:/usr/local/mysql/bin/" & "export DYLD_LIBRARY_PATH=/usr/local/mysql/lib/" -
Django and PosgresSQL adds a timezone offset on every save
My django and postgresql adds the timezone offset to a datetime field on every save. it is working propperly on sqlite. >>> from picture.models import * >>> p=Picture.objects.get(id=561) >>> p.date_taken datetime.datetime(2020, 8, 12, 19, 23, tzinfo=<UTC>) >>> p.save() >>> p=Picture.objects.get(id=561) >>> p.date_taken datetime.datetime(2020, 8, 12, 21, 23, tzinfo=<UTC>) I tried all sorts of configurations combinations in django settings: USE_TZ = True TIME_ZONE = 'UTC' postgresql.conf timezone = 'Etc/UTC' psql ALTER ROLE albumusertest SET timezone TO 'UTC'; some snippets: from postgres date_taken | timestamp with time zone | | not null | django date_taken = models.DateTimeField() postgres version psql (PostgreSQL) 11.12 (Debian 11.12-0+deb10u1) django version 3.2 I am really in a loss. Can anyone help me? -
How can I use Django template syntax in CSS selectors?
I'm pretty new to Django, and I've been wondering about this for a while. Is there any way to put template syntax into a CSS selector, like this: {% for i in list %} <div id='div{{ forloop.counter }}'>test{{ forloop.counter }}</div> <style> #div{{ forloop.counter }} { color: blue; } </style> {% endfor %} And have it produce this code: <div id='div1'>test1</div> <style> #div1 { color: blue; } </style> <div id='div2'>test2</div> <style> #div2 { color: blue; } </style> <div id='div3'>test3</div> <style> #div3 { color: blue; } </style> I tried this, but it just flat out refuses to work. Is there a way to even achieve this, and if so, how?