Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TypeError: argument of type 'PosixPath' is not iterabl
please help i get this error from python manage.py makemigrations Migrations for 'post': post/migrations/0022_auto_20200929_1749.py - Remove field category from post - Remove field tag from post Traceback (most recent call last): File "manage.py", line 22, in main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/lib/python3.8/site-packages/django/core/management/init.py", line 381, in execute_from_command_line utility.execute() File "/usr/lib/python3.8/site-packages/django/core/management/init.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/lib/python3.8/site-packages/django/core/management/base.py", line 336, in run_from_argv connections.close_all() File "/usr/lib/python3.8/site-packages/django/db/utils.py", line 224, in close_all connection.close() File "/usr/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 248, in close if not self.is_in_memory_db(): File "/usr/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 367, in is_in_memory_db return self.creation.is_in_memory_db(self.settings_dict['NAME']) File "/usr/lib/python3.8/site-packages/django/db/backends/sqlite3/creation.py", line 12, in is_in_memory_db return database_name == ':memory:' or 'mode=memory' in database_name TypeError: argument of type 'PosixPath' is not iterabl -
Where should I add more parameters to create a user?
I have followed a tutorial to create an application that only has 1 type of user. In my own app, I'm trying to have multiple types of user, and show different pages according to what type of user they are. I find the teacher in the tutorial isn't very clear and I'm not sure how to differentiate between users. So far, all I need for creating a user is username and password. Also, this article was of help but still made me confused. I want to be able to add more fields but, mainly, differentiate between users (whether they're a Player, Manager or Assistant) during registration. I thought of passing a is_player=true in the POST method for registration but I'm not sure how to add this field to Django registration and then how to create a Player or Manager or Assistant. In my models, I DON'T create a User model, but I create e model for Player, Manager and Assistant # no User model. class Team(models.Model): name = ... ... class Player(models.Model): name = team = models.ManyToManyField(Team) class Manager(models.Model): name = players_responsible_For = models.ManyToManyField(Player) In the serializers file, I DO create a UserSerializer alongside serializers for other models. from django.contrib.auth.models … -
Recommended Editor for Git - Nano or Visual Studio code
I am reading through the Djangogirls.org website and they recommend Nano as the default editor when installing Git. I have also installed Visual Studio Code. I'm want to be efficient if I'm doing django and python in Visual Studio should I just use Visual Studio Code as the default editor? This is the first time I that I'll be using Git or anything similar. It might be that I don't understand it. -
Build passes locally but fails on Travis
I'm going through a Django course right now (recorded online), and we use Travis. I've notices that my builds on Travis fail, even though they pass locally. I've tried to look at different files provided by the instructor an compare it to my code but I can't find any difference. Honestly, this is all very fresh to me so I don't really know even where I should be looking, or what part of the code I should be pasting here for the question. This is the end of the Travis build log: django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "db" (172.18.0.2) and accepting TCP/IP connections on port 5432? The command "docker-compose run app sh -c "python manage.py test && flake8"" exited with 1. Done. Your build exited with 1. And this is my repo: https://github.com/Tsabary/recipe-app-api -
using initial on django MultipleChoiceField on many-to-many relation
In my model, I have: flowcell = models.ForeignKey("FlowCell", on_delete=models.PROTECT) lanes = models.ManyToManyField("main.FlowCellLane", related_name='demuxers', blank=True) in my form, I want these to be selectable, based on available FlowCellLanes. So I pop flowcell to a variable and use it to see which 'Lanes' are there: class DemuxerForm(forms.ModelForm): class Meta: model = Demuxer exclude = ["owner", "pid", "flowcell"] lanes = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple) def __init__(self, *args, **kwargs): self.flowcell = kwargs.pop('flowcell') super().__init__(*args, **kwargs) self.fields['lanes'].choices = sorted([(lane.pk, str(lane.lane_number)) for lane in self.flowcell.lanes.all()]) Now I would like to have all available checkboxes checked. But I don't know how I could do that. At the spot where initial= could be, 'self' is off course not available... any ideas? -
Get Google oauth2 token of users without having google as login option to Django website
I am using gspread to access sheets on behalf of other users. I need to have tokens of the users to do so. I'm fine with users having to give permission on browser one time but dont want Google as signin option to django website. All the search I have done on Oauth2 libraries, they are about making Google as signin option but I just want Google prompting user once to give permission when needed. -
Django orm returning with timezone 0 while I want time zone with specifications
I moved from not using timezone to using timezone but I have a couple of questions about the handling of it. First of all my settings look like this: TIME_ZONE = "Europe/Amsterdam" USE_TZ = True I now get the correct timezone back from the database but not in the right timezone. I suspect that when I have my TIME_ZONE on Europe/Amsterdam that I get that timezone back. But instead I get: 2020-09-27 23:00:07+00:00 But what I want to receive is: 2020-09-27 22:00:00+02:00 I can do this by using timezone.localtime(date_object) But is there a way to get the timezone back in the right format straight from the orm? I am using Postgres 11 and Django 3.0.1 -
How do I run a XMLHttpRequest that relies on another XMLHttpRequest?
I am setting up a social media website where there are posts and comments on posts. The posts and comments are requested using XMLHttpRequest (with a Django, Python backend) here is my post loading code: const xhr = new XMLHttpRequest() const method = 'GET' const responseType = 'json' const url = '/posts' xhr.responseType = responseType xhr.open(method, url) xhr.onload = function() { const serverResponse = xhr.response onst listItems = serverResponse for(var i = 0; i < listItems.length; i++){ var postObj = listItems[i] var currentItem = formatPostElement(postObj) finalPostStr += currentItem // with additional HTML code } postsElement.innerHTML = finalPostStr } xhr.send() // trigger the request This is my code for loading the comments: const xhr = new XMLHttpRequest() const method = 'GET' const responseType = 'json' const url = '/comments' + post_id xhr.responseType = responseType xhr.open(method, url) var input = '' xhr.load = function() { const serverResponse = xhr.response const commentItems = serverResponse for(var q = 0; q < commentItems.length; q++){ input += commentItems[q].content } commentContainerElement.innerHTML = input console.log(input) } xhr.send() The code for the posts grabs every post available in the database. The code for the comments grabs all the comments that are related for a post with post_id. So how … -
Can't login to django admin after successfully creating a super user with a custom user model
imm trying to login to the django admin panel with a successfully created superuser but cannot get the right username/pw combo right. I want users to just use their email as their username. I've deleted migrations, sycndb, and everything works except logging in to the admin panel. models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class MyAccountManager(BaseUserManager): def create_user(self, email, username, password= None): if not email: raise ValueError('email required') if not username: raise ValueError('username required') user = self.model( email= self.normalize_email(email), username= username, ) user.set_password(password) user.save(using= self._db) return user def create_superuser(self, email, username, password): user = self.create_user( email= self.normalize_email(email), password= password, username= username, ) user.is_admin= True user.staff= True user.is_superuser= True user.save(using= self._db) return user class Accounts(AbstractBaseUser): email = models.EmailField(verbose_name= 'email', max_length= 60, unique= True) username = models.CharField(max_length= 30, unique= True) date_joined = models.DateTimeField(verbose_name= 'date joined', auto_now_add= True) last_login = models.DateTimeField(verbose_name= 'last login', auto_now= True) is_admin = models.BooleanField(default= False) is_active = models.BooleanField(default= True) is_staff = models.BooleanField(default= False) is_superuser = models.BooleanField(default= False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = MyAccountManager() def __str__(self): return self.email def has_perm(self, perm, obj= None): return self.is_admin def has_module_perm(self, app_label): return True admin.py from django.contrib import admin from .models import Accounts admin.site.register(Accounts) settings.py INSTALLED_APPS = [ … -
Defining DJANGO_SETTINGS_MODULE
I checked my models.py file for any errors by using the command python models.py check and it returned the following error: django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. So I entered the command: export DJANGO_SETTINGS_MODULE=project1.settings where project1 is the folder directory that contains the settings.py file. I've also tried replacing "project1" with the name of my virtual environment "bugstracker". Both attempts returned the following error: ModuleNotFoundError: No module named 'project1' ModuleNotFoundError: No module named 'bugstracker' What am I missing here? -
How do I pass the value of two separate inputs into the content field of my form in Django?
In my template I have a form that includes two input elements whose values can be adjusted with javascript. I want to be able to take these values and, on form submit, display them in a sentence in a for loop underneath. index.html: <form action="{% url 'workouts:workout' %}" method="post"> {% csrf_token %} <div class="weight"> <h4>WEIGHT (kgs):</h4> <button type="button" class="weight-dec">-</button> <input type="text" value="0" class="weight-qty-box" readonly="" name="one"> <button type="button" class="weight-inc">+</button> </div> <div class="reps"> <h4>REPS:</h4> <button type="button" class="rep-dec">-</button> <input type="text" value="0" class="rep-qty-box" readonly="" name="two"> <button type="button" class="rep-inc">+</button> </div> <input type="submit" value="Save" name="submit_workout"> <input type="reset" value="Clear"> </form> {% if exercise.workout_set.all %} {% for w in exercise.workout_set.all %} {{ w.content }} {% endfor %} {% endif %} I have given the form above an action attribute for a url which maps to a view, and each of the inputs has a name in order to access their values in the view. I also have written this form in forms.py: class WorkoutModelForm(forms.ModelForm): class Meta: model = Workout fields = ['content'] And for context, here is my model: class Workout(models.Model): content = models.CharField(max_length=50) created = models.DateField(auto_now_add=True) updated = models.DateField(auto_now=True) exercise = models.ForeignKey(Exercise, on_delete=models.CASCADE, default=None) class Meta: ordering = ('created',) My problem from here is that I have … -
Django Template - filtering content
I have two models - "Products" and "Categories", and every product may be added to existing category. I am trying to find a way to render page with products, filtered by category. Currently I did it for every category by manualy filtering it in template: {% for instance in object_list %} {% if instance.category.categoryname == "Statues" %} {{ instance.name }} {{ instance.description }} {{ instance.price }} {% endif %} {% endfor %} I have same template for every category ("Paintings", "Jewelry" etc) and changed condition in each template. URL "../Statues" leads to prexisting template Is there any way to do it easier? I would like condtition {% if instance.category.categoryname == "Statues" %} to be imported from URL. So when you access "../Jewelry" - template would import "Jewelry" from URL and filter content accordingly. models.py class Category(models.Model): categoryname = models.CharField(max_length=20) description = models.CharField(max_length=200, blank=True, null=True) #To make in name, not objXXX def __str__(self): return self.categoryname class Product(models.Model): name = models.CharField(max_length=20) image = models.ImageField(upload_to='static/photos', default='http://placehold.it/700x400') description = models.TextField(max_length=200, blank=True, null=True) price = models.DecimalField(decimal_places=2, max_digits=10) category = models.ForeignKey(Category, on_delete=models.PROTECT, blank=True, null=True) #To make in name, not objXXX def __str__(self): return self.name urls.py urlpatterns = [ path('admin/', admin.site.urls), path('<str:categoryname>', category_filter) ] view.py def category_filter(request, … -
Django: searching postgresql JSON field Array of Objects
I have the following json that is appended to a models.JSONField "descriptions": [ { "description": "The Chandra Source Catalog (CSC) is a general purpose virtual X-ray astrophysics facility that provides access to a carefully selected set of generally useful quantities for individual X-ray sources, and is designed to satisfy the needs of a broad-based group of scientists, including those who may be less familiar with astronomical data analysis in the X-ray regime. The first release of the CSC includes information about 94,676 distinct X-ray sources detected in a subset of public Advanced CCD Imaging Spectrometer imaging observations from roughly the first eight years of the Chandra mission. This release of the catalog includes point and compact sources with observed spatial extents ≲30''.", "descriptionType": "Abstract", "lang": "en-US" }, { "description": "The catalog includes real X-ray sources detected with flux estimates that are at least 3 times their estimated 1σ uncertainties in at least one energy band, while maintaining the number of spurious sources at a level of ≲1 false source per field for a 100 ks observation. For each detected source, the CSC provides commonly tabulated quantities, including source position, extent, multi-band fluxes, hardness ratios, and variability statistics, derived from the … -
DjangoCMS copy site slug
we're using djangocms and have german and english pages. Now the slugs for both pages need to be the same. Is there a way to copy the slugs of all german pages to all the english ones without going into the site settings and copy-pasting the german slug to the english slug? I was going for something like manage.py cms copy lang --from-lang=de --to-lang=en --verbosity=2 --skip-content but I haven't tried it yet. Thank you for any help. -
Django ModelFieldChoice select passing value
Hi i'm using ModelFieldChoice to set the foreign key from Provider in the model "Article" (Article belongs to Provider). The select in the template is displayed correctly with all the providers from the database, but when i try to post the form, it throws an error that the select value is required even if i'm passing it. Also i seted values for the article in the database, and when i tried to edit it, all the fields in the form are populated with the correct data except for the select. These are my models, i would appreciate the help, thanks! Sorry if i'm doing something wrong, this is my first time posting in stackoverflow. Article.py Model class Article(models.Model): codigo = models.CharField(max_length=100, verbose_name='Codigo') proveedor = models.ForeignKey(Provider, on_delete=models.CASCADE) descripcion = models.CharField(max_length=200, verbose_name='Descripcion',null=False, blank=True) marca = models.CharField(max_length=100, verbose_name='Marca',null=True, blank=True) rubro = models.CharField(max_length=100, verbose_name='Rubro',null=True, blank=True) nota = models.TextField(verbose_name='Nota',null=True) costo = models.CharField(max_length=50, verbose_name='Costo',null=False, blank=True) created = models.DateTimeField(auto_now_add=True, verbose_name="Fecha de creación",null=True, blank=True) updated = models.DateTimeField(auto_now=True, verbose_name="Fecha de edición",null=True, blank=True) class Meta: verbose_name = "articulo" verbose_name_plural = "articulos" ordering = ['-descripcion'] def __str__(self): return self.descripcion Provider.py Model class Provider(models.Model): razon_social = models.CharField(max_length=100, verbose_name='Razón Social', unique=True) direccion = models.CharField(max_length=100, verbose_name='Dirección', blank=True, null=True) localidad = models.CharField(max_length=100, verbose_name='Localidad', blank=True, null=True) … -
return the absolute url in django media files
I am trying to build graphql api using graphene and when I query an image from my api it returns "/media/images/image.jpg" and I want the full url with the domain name -
Show related model field without adding another fk relation to the model
I've got this 2 models in models.py: class Purity(models.Model): id = models.BigAutoField(db_column='purity_id', primary_key=True) sample = models.ForeignKey(Sample, models.DO_NOTHING) percentage = models.DecimalField(max_digits=10, decimal_places=0, blank=True, null=True) class Sample(AbstractSample): label_commodity = models.ForeignKey(RelatedLabelCommodity, models.DO_NOTHING) user = models.ForeignKey(User, models.DO_NOTHING, related_name='samples') And I'd like to display the purity percentage field in admin.py as: class SampleAdmin(admin.ModelAdmin): list_display = ['---'] Is there any way to this without adding a ForeignKey relationship to Purity in the Sample database table? I found that I could do a sql raw query but it looks also as a security hazard, and I was wondering if there was a better and simpler way. -
Django internationalization doesn't work in my project
I read the documentation, read some blogs and started applying internationalization in my project, but it doesn't work. Probably something is going wrong. Please take a look what is it that I am doing wrong. I am a windows user, so I started installing gettext versions both shared and static from this link. then I made following changes in settings.py: LANGUAGE_CODE = 'fr' MIDDLEWARE = [ "django.middleware.locale.LocaleMiddleware", ... ] LOCALE_PATHS = [ os.path.join(BASE_DIR, 'locale') ] I already set the language code to French language. Then in my template namely index.html I added following code: {% load i18n %} <!-- within block content --> {% trans "Hi" %} Now that everything is set I run following code in console: django-admin makemessages -l fr I received this message: UnicodeDecodeError: skipped file requirements.txt in . (reason: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte) processing locale fr I have no idea if above stated error has anything to do with translating the text of the template. Anyway, then in django.po within locale directory I translated that text of template to french as following: #: .\templates\index.html:29 msgid "Hi" msgstr "Salut" and run django-admin compilemessages, but when I run it the … -
How to add custom permissions to token authentication in Django rest framework
I've built an endpoint using Django-rest-framework and I've added token authentication to it by simply adding rest_framework.authentication.TokenAuthentication to the DEFAULT_AUTHENTICATION_CLASSES. This works great. Without the token I get a 403 and with it I get the expected 201. I now want to add a custom permission to it, so I did the following: class CustomPermission(BasePermission): def has_permission(self, request, view): breakpoint() return False def check_permission(self, user): breakpoint() return False class MyViewSet(DetailSerializerMixin, viewsets.ModelViewSet): queryset = MyModel.objects.all().order_by('timestamp') http_method_names = ['post'] permission_classes = [CustomPermission] To my surprise this doesn't do anything. It never reaches the breakpoints and works exactly as without it. Does anybody know what I'm doing wrong here? -
Getting Image from Page Link for django application
I have json file and it contain "Product_url": "https://www.amazon.in/Samsung-Galaxy-Storage-Additional-Exchange/dp/B07PQ7CRBH/ref=sr_1_11?keywords=phone&qid=1563166792&s=electronics&smid=A14CZOWI0VEHLG&sr=1-11", How to get image from this like below one https://images-na.ssl-images-amazon.com/images/I/71ftMiKUwbL._SL1500.jpg -
Registration and login to Django website with mobile app
i have a website running on django(postgresql db) and now i'm developing mobile app with xamarin forms. i've created web api with asp.net core and successfully consume data from website. my question is how can i make registration and login to website from my app. i added username, password and email to postgresql db through web api, but i can't login to website using these credentials. it says incorrect password or username. is it a right way to insert user data to db? my app code: public async void Reg_Clicked(object sender, EventArgs e) { Dictionary<string, string> userData = new Dictionary<string, string> { { "username", EntryUsername.Text }, { "email", EntryEmail.Text }, {"password1", EntryPassword1.Text }, {"password2", EntryPassword1.Text }, }; var jsonData = JsonConvert.SerializeObject(userData, Formatting.Indented); Console.WriteLine(jsonData); // Создать Http-клиент для подключения HttpClient client = new HttpClient(); var content = new StringContent(jsonData, Encoding.UTF8, "application/json"); try { HttpResponseMessage response = await client.PostAsync("https://localhost/api/UserData", content); var result = await response.Content.ReadAsStringAsync(); Console.WriteLine(result); } catch (Exception) { Console.WriteLine("Failure"); } } my web api code: public async Task<ActionResult<UserData>> PostUserData(UserData userData) { _context.UserDatas.Add(userData); await _context.SaveChangesAsync(); //put in database string connectionString = "Server=server; Port=5432; User Id=user; Password=password; Database=database"; try { connection = new NpgsqlConnection(connectionString); connection.Open(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } … -
DELETE method not responding if run in docker
I have a django application that runs with docker. I use postgres as a database. Any call GET, PUT and POST work great. The main problem here is that when I do any call to an endpoint that should delete something from the database it deletes the data, but it dosen't respond. If I call the endpoint and right after check the database, the data is gone, but the delete call remains in waiting. The situation is different if I run the django application outside the docker (even if I use the postgres dockerized) because the delete endpoints work perfectly and they reply me right after with the correct message.. my docker file is # pull official base image FROM python:3.8.0-alpine # create directory for the app user RUN mkdir -p /home/app # create the app user RUN addgroup -S app && adduser -S app -G app ENV APP=/home/app RUN mkdir $APP/staticfiles RUN mkdir $APP/mediafiles RUN mkdir $APP/files WORKDIR $APP # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 ENV PIPENV_TIMEOUT 3600 # Psycopg dependencies RUN apk update \ && apk add postgresql-dev gcc python3-dev musl-dev openssl-dev libffi-dev libc-dev gcc libxslt-dev # Install dependencies RUN pip install --upgrade pip … -
Cannot resolve keyword 'some_field' into field. Choices are:
I am filtering the Model by related Model but I am encountering some errors specified in the question title. Cannot resolve keyword 'bmodel' into field. Choices are: title, description, number, client_user_id, assignee_id Models are like that: 1st model class AModel(BaseModel): title = models.TextField(null=True, blank=True) description = models.TextField(null=True) number = models.CharField(max_length=200) client_user = models.ForeignKey("User", related_name="client_users", null=True) assignee = models.ForeignKey("User", related_name="user_assignees", null=True) 2nd model class BModel(models.Model): amodel = models.ForeignKey("AModel", related_name="a_model", on_delete=DO_NOTHING) user = models.ForeignKey("User", related_name="entity_user") my queryset class AModelView(GenericViewSet): queryset = AModel.objects.all() serializer_class = AmodelSerializer def get_queryset(self): current_user = 2 qs = super().get_queryset() qs = qs.filter(bmodel__user_id__in=current_user) return qs How can I solve this issue? can anybody help please? Thanks in advance! -
return filtered query-set using Django-Graphene
i'm trying to return filtered results using django-graphene but it gives error about error-message could anyone please let me know why this happening class PatientType(DjangoObjectType): class Meta: model = Patients exclude = ('active',) interfaces = (relay.Node,) class PatientsQuery(ObjectType): get_patient = graphene.Field(PatientType, id=graphene.Int()) all_patients = graphene.List( PatientType, first=graphene.Int(), skip=graphene.Int(), phone_no=graphene.Int() ) upcoming_appointments = DjangoFilterConnectionField(PatientType) @permissions_checker([IsAuthenticated, CheckIsOrganizationActive]) def resolve_upcoming_appointments(self, info, **kwargs) -> List: d = datetime.today() - timedelta(hours=1) settings.TIME_ZONE # 'Asia/Karachi' aware_datetime = make_aware(d) res = Patients.objects.filter(appointments__booking_date__gte=aware_datetime, appointments__booking_date__day=aware_datetime.day, appointments__status=True) if res: return res return [] class Query( organization_schema.OrganizationQuery, inventory_schema.MedicineQuery, patient_schema.PatientsQuery, graphene.ObjectType, ): -
Django orm remove overlapping date_ranges
I'm new to django & I have a table with multiple entries of different date_ranges. I want to get only the unique ranges & then get Count of numbers of days from them. For example Consider following three ranges: 1. 10-09-2017 to 10-09-2019 2. 10-08-2018 to 10-02-2020 2. 04-04-2020 to 04-04-2020 In the above example 1 & 2 have overlapping dates, actual calculation for point 2 should change start_range to the end_range of point 1 and then calculate days based on that (I know it can be a little confusing and I'm happy to explain it further if required) I can use something like following to get difference in days for each date_range calculate_experience = ExpressionWrapper( Case( When(experiences__end__isnull=True, then=date.today()-F('start'))[0].days, default=F('end')-F('start')), distinct=True, filter=Q(is_active=True), output_field=DurationField() ) But I have no idea how to get only unique ranges from this, the only thing that comes to mind is putting these in a list & then iterating over that manually settings ranges & then calculating the difference. Is there a better way to do this? Any help or sense of direction is much appreciated. Thanks!